package com.example.flowable.info;

import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.runtime.ProcessInstanceQuery;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Foolish
 * @description
 * @date: 2018/9/25 15:01
 */
@RestController
@RequestMapping (value = "flowable")
public class InfoController {

    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;



    /**
     * 系统流程部署列表
     */
    @RequestMapping (value = "list")
    public GritResult flowableList() {
        List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery().list();
        List<Process> list = new ArrayList<>();
        for(ProcessDefinition pd:pdList){
            Process p = new Process(pd);
            System.out.println(p);
            System.out.println("===================");
            list.add(p);
        }

        GritResult gr = new GritResult("success",list.size(),list);
        return gr;
    }

    /**
     * 删除系统部署的流程
     */
    @RequestMapping (value = "remove")
    public String remove(String id) {
        repositoryService.deleteDeployment(id);
        return "删除成功";
    }

    /**
     * 获取流程实例
     */
    @RequestMapping (value = "instance/list")
    public GritResult instanceList(String userId) {
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        if(!StringUtils.isEmpty(userId)){
            query.startedBy(userId);
        }

        List<ProcessInstance> processInstanceList = query.list();
        List<ProcessIn> list = new ArrayList<>();
        for (ProcessInstance pi : processInstanceList) {

            ProcessIn pp = new ProcessIn(pi);
            System.out.println(pp.toString());
            list.add(pp);
        }
        GritResult gr = new GritResult("success",list.size(),list);
        return gr;
    }

    /**
     * 删除流程实例
     */
    @RequestMapping (value = "instance/remove")
    public String removeInstance(String id) {
        runtimeService.deleteProcessInstance(id, "删除测试");
        return "删除成功";
    }

    /**
     * 获取任务列表
     */
    @RequestMapping (value = "task/list")
    public GritResult taskList(String userId, String group) {
        TaskQuery query = taskService.createTaskQuery();
        if(!StringUtils.isEmpty(group)){
            query.taskCandidateGroup(group);
        }else if(!StringUtils.isEmpty(userId)){
            query.taskCandidateOrAssigned(userId);
        }

        List<Task> tasks = query.orderByTaskCreateTime().desc().list();
        List<FlowableTask> list = new ArrayList<>();
        for (Task task : tasks) {
            FlowableTask ft = new FlowableTask(task);
            System.out.println(ft.toString());
            list.add(ft);
        }
        GritResult gr = new GritResult("success",list.size(),list);
        return gr;
    }

    /**
     * 删除任务
     */
    @RequestMapping (value = "task/remove")
    public String removeTask(String id) {
        taskService.deleteTask(id);
        return "删除成功";
    }

    /**
     * 获取历史任务列表
     */
    @RequestMapping (value = "historic/list")
    public GritResult historicTaskList(String userId) {
        HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();
        if(!StringUtils.isEmpty(userId)){
            query.involvedUser(userId);
        }
        query.finished();
        List<HistoricProcessInstance> hpis = query.orderByProcessInstanceEndTime().desc().list();
        List<HistoricProcessInstance_> list = new ArrayList<>();
        for (HistoricProcessInstance hpi : hpis) {
            HistoricProcessInstance_ ft = new HistoricProcessInstance_(hpi);
            System.out.println(ft.toString());
            list.add(ft);
        }
        GritResult gr = new GritResult("success",list.size(),list);
        return gr;
    }

    /**
     * 获取历史任务列表
     */
    @RequestMapping (value = "historic/my/list")
    public GritResult historicMyTaskList(String userId) {
        HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();
        if(!StringUtils.isEmpty(userId)){
            query.involvedUser(userId);
        }
        query.finished();
        List<HistoricProcessInstance> hpis = query.orderByProcessInstanceEndTime().desc().list();
        List<HistoricProcessInstance_> list = new ArrayList<>();
        for (HistoricProcessInstance hpi : hpis) {
            HistoricProcessInstance_ ft = new HistoricProcessInstance_(hpi);
            System.out.println(ft.toString());
            list.add(ft);
        }
        GritResult gr = new GritResult("success",list.size(),list);
        return gr;
    }

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @RequestMapping(value = "processDiagram")
    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
